package com.fs.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fs.pandaFund.common.exception.ExistPhoneException;
import com.fs.pandaFund.common.exception.UsernameAndPasswodErrorException;
import com.fs.pandaFund.common.exception.invalidVerifyCodeException;
import com.fs.pandaFund.common.pojo.User;
import com.fs.pandaFund.common.util.PasswordUtils;
import com.fs.user.mapper.UserMapper;
import com.fs.user.service.UserService;
import com.fs.user.util.TokenUtil;
import com.fs.user.util.UserContext;
import com.fs.user.vo.LoginBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Author:HOU
 * date:2023/2/11  17:19
 * 案例:
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void enroll(User user) {
        userMapper.insert(user);
    }

    @Override
    public void ifExistPhone(String phone) throws ExistPhoneException {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUid,phone);
        List<User> users = userMapper.selectList(queryWrapper);
//        System.out.println(users.get(0).getUpassword());
        if(!users.isEmpty()){
            throw new ExistPhoneException();
        }
    }

    @Override
    public void loginByPassword(LoginBean loginBean) throws Exception {
        String VerifyCode= UserContext.getVerifyCode();
        if (StringUtils.isEmpty(VerifyCode)){
            throw new invalidVerifyCodeException();
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUid,loginBean.getUsername());
        List<User> users = userMapper.selectList(queryWrapper);

        if (!users.isEmpty()){
            if (PasswordUtils.verify(loginBean.getPassword(), users.get(0).getUpassword())){
                String token= TokenUtil.randomToken();
                String key="loginUser"+ token;
//                LoginUserDTo loginUserDTo = BeanUtil.copyProperties(admin, LoginUserDTo.class);
//                //redisTemplate.opsForValue()
//                Map<String, Object> map = BeanUtil.beanToMap(loginBean, false, true);
//                redisTemplate.opsForHash().putAll(key,map);
//                redisTemplate.expire(key,30, TimeUnit.MINUTES);
//                return token;

            }


        }
        throw  new UsernameAndPasswodErrorException();

//        if (PasswordUtils.verify(password, users.get(0).getUpassword())){
//            return ;
//
//        }
//        else {
//
//        }

    }


}
